package projet;

import projet.database.Database;
import projet.database.DatabaseAccess;

/**
 * Main class, try to log someone to the database using databaseaccess
 * 
 * @author CORSINI Pierre, Cyril CHANDELIER, Sylvain BRUN
 * @version January 25, 2010
 */
public class MainClass {
	public static void main(String[] args) {
		Database database = null;
		try {
			String path = Tools.getExecutionPath()
					+ System.getProperty("file.separator") + "thedatabase";
			database = new Database(path);
		} catch (CustomException e) {
			e.display();
			Tools.printerr("Exiting !");
			System.exit(-1);
		}
		DatabaseAccess da = new DatabaseAccess(database);

		String[] query_arr;
		String query;
		String separator = " ";

		while (true) {
			Tools.print("Database access, options:");
			Tools.print(2, "login <username> <password>");
			Tools.print(2, "createuser <username> <password> <password>");
			Tools.print(2, "quit");

			query = Tools.readLine();

			query_arr = query.split(separator);

			// Create user section
			if (query_arr[0].equalsIgnoreCase("createuser")) {
				if (query_arr.length != 4) {
					Tools
							.printerr("User creation error, argument number missing !");
					continue;
				}

				try {
					da.createUser(query_arr[1], query_arr[2], query_arr[3]);
					Tools.print("User " + query_arr[1] + " created !");
				} catch (CustomException e) {
					e.display();
				}
				

				continue;
			}

			// User login section
			else if (query_arr[0].equalsIgnoreCase("login")) {
				if (query_arr.length != 3) {
					Tools.printerr("Login error, argument number error !");
					continue;
				}
				try {
					da.log(query_arr[1], query_arr[2]);
				} catch (CustomException e) {
					e.display();
					Tools.printerr("You are not logged !");
					continue;
				}

				// Here we are logged
				da.startSession();

			}

			// QUit
			else if (query_arr[0].equalsIgnoreCase("quit")) {
				break;
			} else
				Tools.printerr("Bad commannd !");
			Tools.print("");
		}

		// End of loop
		Tools.print("Quiting application !");
	}
}
